#!/bin/bash
log_file=/home/pi/logs/netrestart_log
exec_path=/home/pi/siweather/scripts

# Use 'wvdial' or 'network-manager'
connection_app='wvdial'

running=`ps -e | grep netrestart | wc -l`
if [ $running -gt 2 ]; then 
	echo "Already running, counted $running processes"	
	exit 0
fi

if [ "$connection_app" = "wvdial" ]; then
	sudo service network-manager stop &> /dev/nul
	process=`ps -e | grep wvdial`
	while [ -n "$process" ]; do
		sudo killall wvdial &> /dev/nul
		sleep 1
		process=`ps -e | grep wvdial`
	done

	$exec_path/modem_reset
	sleep 10

	sierra=`lsusb | grep "Sierra Wireless"`
	zte=`lsusb | grep "ONDA Communication"`

	if [ -n "$sierra" ]; then
		device_path="/dev/"`$exec_path/get_sierra306`
		echo "Found sierra 306 3G modem"
	elif [ -n "$zte" ]; then
		device_path="/dev/"`$exec_path/get_mf626`
		echo "Found zte mf626 3G modem"
	else 
		echo "No 3G device present"
		exit 0
	fi
	
	sudo wvdial "Modem = $device_path" > /tmp/wvdial.log 2>&1 &
	sleep 18
	connected=`cat /tmp/wvdial.log | grep "local  IP address"`
	if [ -z "$connected" ]; then
		cp /tmp/wvdial.log /home/pi/logs/bad_wvdial_on_`date +%d_%m_%y__%H_%M_%S`
		sudo killall wvdial
		$exec_path/modem_reset
		echo "On "`date`", failed to connect using wvdial, restarted the modem. See 'bad_wvdial_on_"`date +%d_%m_%y__%H_%M_%S`"' for wvdial output." >> $log_file
		exit 1
	fi
	echo -e "\nStarted wvdial\n"

elif [ "$connection_app" = "network-manager" ]; then
	NM=`sudo status network-manager | grep start`
	if [ -n "$NM" ]; then
		sudo stop --quiet network-manager
		sleep 5
	fi

	sudo start --quiet network-manager
	sleep 3

else 
	echo "Invalid connection application"; 
	exit 1; 
fi

COUNT=1
LIM=10

CHECK=`sudo $exec_path/pppcheck`
while [ $CHECK = "no" -a $COUNT -lt $LIM ]; do
	COUNT=`expr $COUNT + 1`
	sleep 1
	CHECK=`sudo $exec_path/pppcheck`
done

if [ $COUNT -lt $LIM ]; then
	sleep 2
else
	sudo killall wvdial
	$exec_path/modem_reset
	echo "On "`date`", wvdial connected but pppcheck failed (10 times), restarted the modem." >> $log_file
	exit 1
fi



IP=`$exec_path/getip`
reply=`sudo noip2 -i "$IP" 2>&1`
if [ "$?" = "1" ]; then 
	echo -e "On "`date`" the noip2 update failed with error: \n"$reply >> $log_file
	exit 1
else 
	echo "Sent IP address ("$IP") to no-ip.com"
fi

sudo route del default
sleep 1
sudo route add default dev ppp0

exit 0
